package cl.crabcom.shoppinglist;

import static android.provider.BaseColumns._ID;
import static cl.crabcom.accessdata.Constants.NAME;
import static cl.crabcom.accessdata.Constants.TABLE_NAME;
import static cl.crabcom.accessdata.Constants.TIME;
import cl.crabcom.accessdata.MarketData;
import android.app.ListActivity;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.ArrayAdapter;
import android.widget.ListView;

public class ShowStore extends ListActivity  {
	
	 private static String[] FROM = { _ID, TIME, NAME, };
	 private static String ORDER_BY = TIME + " DESC";	
	 private MarketData stores;
	
	 public void onCreate(Bundle savedInstanceState) {
		
		super.onCreate(savedInstanceState);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		
		super.onCreateOptionsMenu(menu);
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.menu, menu);
		return true;
	}	
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		
		switch (item.getItemId()) {
		
			case R.id.new_market:
				startActivity(new Intent(this, NewStore.class));
				return true;
		}
		return false;
	}

	private Cursor getStore() {

		SQLiteDatabase db = stores.getReadableDatabase();
		Cursor cursor = db.query(TABLE_NAME, FROM, null, null, null, null,ORDER_BY);
		startManagingCursor(cursor);
		return cursor;
	}	
	
	private String[] showStore(Cursor cursor) {
		
		String arrays[] = new String[cursor.getCount()];
		int count = 0;
		
		while (cursor.moveToNext()) {
		
			
			arrays[count] = cursor.getString(2);
			count++;
		}
		
		return arrays;
	}

	@Override
	protected void onResume() {

		super.onResume();	
		stores = new MarketData(this);	
		Cursor cursor = this.getStore();
		String[] store = this.showStore(cursor);
		
		setListAdapter(new ArrayAdapter<String>(this, R.layout.showstore, store));
		ListView listadoTiendas = getListView();
		listadoTiendas.setTextFilterEnabled(true);
		
		stores.close();
	}
}
